mongoose = require "mongoose"
Config= require "../bin/config/configure"

# mongodb 时区问题：
#   Date.parse("2015-09-09T15:00:00.000Z") + offset
mongoose.offset = new Date().getTimezoneOffset() * 60000

# mongoose处理时间默认在八小时之前
mongoose.dateHandle = ->
  date = new Date()
  date.setHours(date.getHours() + 8)
  return date.getTime()


mongoose.connection.once "open", ->
  console.info "mongodb is opened..."

# Error handler
mongoose.connection.on "error", (err) ->
  console.error "mongodb exception: #{err}"

# app crash
process.on 'SIGINT', ->
  mongoose.connection.close ->
    console.warn  'mongodb disconnected through app termination'
    process.exit 0

# Reconnect when closed
count = 0
mongoose.connection.on "disconnected", ->
  console.warn "mongodb disconnected... reconneting #{count} seconds "
  count++
  if count <= 5
    setTimeout connect, 5000
  else
    process.exit 1


###
[connect description]  Connect to mongodb
@return {[type]} [description]
###
connect = ->
  # All executed collection methods will log output of their arguments to your console.
  mongoose.set('debug', false) unless process.env.NODE_ENV == 'production'

  _config= Config.getConfig().mongoose
  # mongoose.connect 'mongodb://182.92.213.197/appbricks', options
  mongoose.connect "#{_config.url}:#{_config.port}/#{_config.db}", _config.options

# start connect...
connect()


### 创建数据库连接，不自动重连，连接失效后由业务决定重连
[createConnection description]  create connection
@return {[type]} con [description] con.model(...);
###
exports.createConnection = (url, options) ->
  unless url
    console.log "无效配置：url=#{url}, options=#{options}"
    return

  db = mongoose.createConnection url, options

  db.once "open", ->
    console.info "\n\t#{url} is opened...\n"
  # Error handler
  db.on "error", (err) ->
    console.error "\n\t #{url} exception: #{err}\n"


exports.mongoose = mongoose
